#-*- coding: utf-8 -*-
from django.http import HttpResponse, HttpResponseRedirect
from google.appengine.api import images
from google.appengine.ext import db
from models.main import App_user, Post, Comment, Tag

from common.view_decorator import role_required
from logics.main import get_user, set_user
import datetime
import django

from django.conf import settings

import ai

def get_django_version():
    #(1, 0, 'alpha')
    return django.VERSION[0]

class Images(db.Model):
    uploader = db.ReferenceProperty(App_user)
    content = db.BlobProperty()
    image_type = db.StringProperty()
    add_time = db.DateTimeProperty()

@role_required('admin')
def upload_image(request):
    img = Images()

    img_file = request.FILES.get('img')
    if not img_file:
        return HttpResponse('{status:"Please select your image."}')

    img.uploader = get_user()
    img.add_time = datetime.datetime.utcnow()

    if get_django_version() >= 1:
        content = img_file.read()
        file_path = img_file.name
    else:
        content = img_file['content']
        file_path = img_file['filename']

    img.content = db.Blob(content) 
    img.image_type = ai.get_content_type(file_path)
    key = img.put()
    return HttpResponse('{status:"UPLOADED",image_url: "/rpc/img/?img_id=%s"}' % (key))

def img(request):
    img = db.get(request.GET["img_id"])
    if img and img.content:
        return HttpResponse(img.content, mimetype=img.image_type)
    else:
        return HttpResponse("No image")